import React, { FC, useEffect, useRef, useState } from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import { get } from "lodash";

const VideoEl: FC<{
  source: string;
  pointList?: [number, number][];
  width?: number;
  height?: number;
  showControl?: boolean;
}> = ({ source, showControl, pointList, width = 700, height = 400 }) => {
  const videoRef = useRef<HTMLMediaElement>();
  const [duration, setDuration] = useState(0);
  const playerRef = useRef();

  React.useEffect(() => {
    if (!playerRef.current) {
      const videoElement = document.createElement("video-js");

      videoElement.classList.add("vjs-big-play-centered");
      videoRef.current.appendChild(videoElement);

      playerRef.current = videojs(videoElement, {
        controls: true,
        width,
        height,
        controlBar: {
          volumePanel: {
            inline: false,
            volumeControl: {
              vertical: true,
            },
          },
        },
      });

      // new VolumeControl(playerRef.current, {
      //   vertical: true
      // })
    }

    playerRef.current.src(source);
    const player = playerRef.current;
    if (!player) return;
    player.on("durationchange", () => {
      // console.log(player.duration(), 'player.duration()')
      setDuration(player.duration());
    });
  }, [source, videoRef]);
  useEffect(() => {
    const player = playerRef.current;
    if (!duration || !player) return;
    if (!player.el_) return;
    const targetEl = player.el_.querySelector(".vjs-progress-holder");
    !!showControl && player.el_.classList.add("vjs-has-started");
    if (!targetEl) return;
    let pointerEl = targetEl.querySelector(".vjs-pointer-wrapper");
    if (!pointerEl) {
      pointerEl = document.createElement("div");
      pointerEl.classList.add("vjs-pointer-wrapper");
      targetEl.append(pointerEl);
    }
    pointerEl.innerHTML = "";
    const virtualEl = document.createDocumentFragment();
    pointList.forEach(([start, end]) => {
      const width = ((end - start) / duration) * 100 + "%";
      const left = (start / duration) * 100 + "%";
      const el = document.createElement("div");
      el.style.width = width;
      el.style.left = left;
      el.classList.add("vjs-pointer-item");
      virtualEl.append(el);
    });

    pointerEl.append(virtualEl);
  }, [playerRef, pointList, duration]);

  // const prevPointListRef = useRef<any>();
  useEffect(() => {
    const player = playerRef.current;
    // if (player && prevPointListRef.current && prevPointListRef.current !== pointList) {
      const hopeTime = get(pointList,'[0][0]', 0);
      player?.currentTime?.(hopeTime)
    // }
    // prevPointListRef.current = pointList;
  }, [playerRef, pointList]);
  return (
    <div data-vjs-player>
      <div ref={videoRef} />
    </div>
  );
};

export default VideoEl;
